//
//  UIColor+HexString.swift
//  clreader
//
//  Created by colin on 2019/2/26.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

extension UIColor {
    
    convenience init(hex:String) {
        self.init(hex: hex,alpha: 1.0)
    }
    
    convenience init(hex:String,alpha:CGFloat) {
        let hexint = Int(UIColor.intFrom(hexStr: hex))
        let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
        let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
        let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    private static func intFrom(hexStr: String) -> UInt32 {
        var hexInt: UInt32 = 0
        // Create scanner
        let scanner: Scanner = Scanner(string: hexStr)
        // Tell scanner to skip the # character
        scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
        // Scan hex value
        scanner.scanHexInt32(&hexInt)
        return hexInt
    }
}
